
import styles from "./role.module.scss"
import React, {useEffect, useState} from "react";
import {addRecord, queryRecordList} from "@/apis/index"
import {FormDataWithFile, Record} from "@/types/role";
import {
    Input,
    Button,
    Upload,
    List,
    Avatar,
    UploadFile,
    UploadProps,
    Space,
    Image,
    Typography
} from "antd";
import {LikeOutlined, MessageOutlined, StarOutlined, UploadOutlined} from '@ant-design/icons';
import {SaleProductEnum} from "@/types/sale_product";
import {useAccessStore} from "@/app/store/access";


export function Role() {
    const { Text, Link } = Typography;
    // 是否显示新增
    const [showModal, setShowModal] = useState(false);
    // 封装接口调用返回来的商品列表
    const [record,setRecord] = useState<Record[]>([])
    // 已经上传的文件列表
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [formData, setFormData] = useState<FormDataWithFile>({
        title: '',
        address: '',
        description: '',
        imageUrl: '',
    });

    const IconText = ({ icon, text }: { icon: React.FC; text: string }) => (
        <Space>
            {React.createElement(icon)}
            {text}
        </Space>
    );
    const add = () => {
        console.log("---------------->触发新增")
        // 设置状态
        setShowModal(true);
    }
    const addRecordHandler = async  () => {

        const res = await addRecord(formData)
        const {data,code} = await res.json()
        // 登录拦截
        if (code === SaleProductEnum.NeedLogin) {
            useAccessStore.getState().goToLogin();
        }
        // 新增成功
        if (code == SaleProductEnum.SUCCESS) {
            setShowModal(false);
            queryRecordListHandler().then(res => {
               console.log("新增成功-记录列表数据加载完成")
            })
        }
    }
    const submit = () => {
        console.log("---------------->触发提交",formData)
        addRecordHandler().then((res) => {
            console.log("新增返回结果：",res)
        })
    }
    const queryRecordListHandler = async () => {
        const res = await queryRecordList()
        const {data,code} = await res.json()
        // 登录拦截
        if (code === SaleProductEnum.NeedLogin) {
            useAccessStore.getState().goToLogin();
        }
        setRecord(data)
    }

    useEffect(() => {
        queryRecordListHandler().then(res => {
            console.log("记录列表数据加载完成")
            console.log(res)
        })
    }, [])

    const handleChange: UploadProps['onChange'] = (info) => {
        let newFileList = [...info.fileList];
        newFileList = newFileList.map((file) => {
            if (file.response) {
                file.url = file.response.data;
            }
            return file;
        });
        setFileList(newFileList);

        const urlList: string[] = newFileList
            .map((file) => (file.url ? file.url : undefined))
            .filter((url): url is string => url !== undefined);

        const commaSeparatedUrls = urlList.join(',');
        setFormData({...formData, imageUrl: commaSeparatedUrls})

    };

    const props = {
        action: 'http://openaighl.com.cn:8090/api/v1/file/uploads',
        onChange: handleChange,
        multiple: true,
    };
        return (
            <div className={styles.role}>
                <div className={styles["record-desc"]} onClick={() => add()}>
                    广告页
                </div>

                {
                   !showModal && (
                        <List
                            itemLayout="vertical"
                            size="large"
                            pagination={{
                                onChange: (page) => {
                                    console.log(page);
                                },
                                pageSize: 3,
                            }}
                            dataSource={record}
                            footer={
                                <div>
                                    <b>ant design</b> footer part
                                </div>
                            }
                            renderItem={(item) => (
                                <List.Item
                                    key={item.title}
                                    actions={[
                                        <IconText icon={StarOutlined} text="156" key="list-vertical-star-o" />,
                                        <IconText icon={LikeOutlined} text="156" key="list-vertical-like-o" />,
                                        <IconText icon={MessageOutlined} text="2" key="list-vertical-message" />,
                                    ]}
                                    extra={
                                        <Image.PreviewGroup
                                            items={item.imageUrlArray}
                                        >
                                            <Image
                                                width={300}
                                                height={180}
                                                src={item.imageUrl}
                                            />
                                        </Image.PreviewGroup>
                                    }
                                >
                                    <List.Item.Meta
                                        avatar={<Avatar src="https://api.dicebear.com/7.x/miniavs/svg?seed=1" />}
                                        title={<Link href={item.address}>{item.title}</Link>}
                                        description={<b>项目地址：<a href={item.address}>{item.address}</a></b>}
                                    />
                                    <b>{item.description}</b>
                                </List.Item>
                            )}
                        />
                    )
                }


                {
                   showModal && (
                        <>
                            <div className={styles.from}>
                                主题：<Input placeholder="主题" name="主题" value={formData.title} onChange={(e) => setFormData({...formData, title: e.target.value})}/>
                            </div>
                            <div className={styles.from}>
                                地址： <Input placeholder="项目地址" name="项目地址" value={formData.address} onChange={(e) => setFormData({...formData, address: e.target.value})}/>
                            </div>
                            <div className={styles.area}>
                                描述：<Input.TextArea
                                value={formData.description}
                                onChange={(e) => setFormData({...formData, description: e.target.value})}
                                className={styles.textarea}
                                placeholder={"请输入项目描述"}
                                autoFocus
                            />
                            </div >
                            <div className={styles.from}>
                                <Upload {...props} fileList={fileList}>
                                    <Button icon={<UploadOutlined />}>选择文件</Button>
                                </Upload>
                            </div>

                            <div  className={styles.from}>
                                <Button type="primary" onClick={()=>{
                                    submit()
                                }}>提 交 </Button>
                            </div>
                        </>
                    )
                }










            </div>
        )
    }
